/*
 * Copyright 2011 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package fr.gaellalire.jzip.test.macosx;

import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.peer.DragSourceContextPeer;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.awt.peer.ComponentPeer;
import java.io.File;
import java.util.List;
import java.util.Map;

import org.rococoa.cocoa.foundation.NSString;

import sun.awt.dnd.SunDropTargetContextPeer;
import apple.awt.CImage;
import apple.awt.CToolkit;
import apple.awt.ComponentModel;

@SuppressWarnings({"restriction", "unused", "rawtypes", "deprecation"})
public class ExtendedCDragSourceContextPeer extends sun.awt.dnd.SunDragSourceContextPeer {

    // private static final CDragSourceContextPeer fInstance;
    private Image fDragImage;
    private CImage fDragCImage;
    private Point fDragImageOffset;
    private static double fMaxImageSize = 128.0D;
    DragSourceContextPeer createDragSourceContextPeer;

    private static CToolkit cToolkit = new CToolkit();

//    static {
//        try {
//            Field declaredField = CDragSourceContextPeer.class.getDeclaredField("fInstance");
//            declaredField.setAccessible(true);
//            fInstance = (CDragSourceContextPeer) declaredField.get(null);
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new RuntimeException(e);
//        }
//    }

    public ExtendedCDragSourceContextPeer(final DragGestureEvent dragGestureEvent) {
        super(dragGestureEvent);
        createDragSourceContextPeer = cToolkit.createDragSourceContextPeer(dragGestureEvent);
    }

    @Override
    protected void setNativeCursor(final long arg0, final Cursor arg1, final int arg2) {

    }

    @Override
    protected void startDrag(final Transferable paramTransferable, final long[] paramArrayOfLong, final Map paramMap) {
        DragGestureEvent localDragGestureEvent = getTrigger();
        InputEvent localInputEvent = localDragGestureEvent.getTriggerEvent();

        Point localPoint1 = localDragGestureEvent.getDragOrigin();
        int i = localInputEvent.getModifiers() | localInputEvent.getModifiersEx();
        long l1 = localInputEvent.getWhen();
        int j = (localInputEvent instanceof MouseEvent) ? ((MouseEvent) localInputEvent).getClickCount() : 1;

        Component localComponent = localDragGestureEvent.getComponent();
        Point localPoint2 = new Point();
        ComponentPeer localComponentPeer = localComponent.getPeer();

        if (localComponent.isLightweight()) {
            Point localObject = localComponent.getLocation();
            localPoint2.translate((localObject).x, (localObject).y);

            for (Container localContainer = localComponent.getParent(); localContainer != null; localContainer = localContainer.getParent()) {
                if (!localContainer.isLightweight()) {
                    localComponentPeer = localContainer.getPeer();
                    break;
                }

                localObject = localContainer.getLocation();
                localPoint2.translate((localObject).x, (localObject).y);
            }

        }

        if (!(localComponentPeer instanceof ComponentModel)) {
            throw new IllegalArgumentException("DragSource's peer must be a ComponentModel.");
        }

        Object localObject = localComponentPeer;
//        long l2 = ((ComponentModel) localObject).getModelPtr();

        Cursor localCursor = getCursor();

        if (this.fDragImage == null) {
           // setDefaultDragImage(localComponent);
        }
        long l3;
        Point localPoint3;
        if (this.fDragImage != null) {
            BufferedImage localBufferedImage = (this.fDragImage instanceof BufferedImage) ? (BufferedImage) this.fDragImage : null;

            if (localBufferedImage == null) {
                int k = this.fDragImage.getWidth(null);
                int m = this.fDragImage.getHeight(null);
                localBufferedImage = new BufferedImage(k, m, 3);

                Graphics localGraphics = localBufferedImage.getGraphics();
                localGraphics.drawImage(this.fDragImage, 0, 0, null);
                localGraphics.dispose();
            }

//            this.fDragCImage = CImage.getCreator().createImage(localBufferedImage);
//            l3 = this.fDragCImage.getNSImage();
            localPoint3 = this.fDragImageOffset;
        } else {
            this.fDragCImage = null;
            l3 = 0L;
            localPoint3 = new Point(0, 0);
        }

//        long l4 = this.fDragCImage != null ? this.fDragCImage.getNSImage() : 0L;
        /*
        try {
            NSEvent event = NSApplication.sharedApplication().currentEvent();
            NSView view = event.window().contentView();
            writeItemsToPasteBoard(view, Arrays.asList("youpi"));

//            long l5 = createDragSourceContextPeer.createNativeDragSource(localComponent, localComponentPeer, l2, paramTransferable, localInputEvent,
//                    (int) (localPoint1.getX() + localPoint2.x), (int) (localPoint1.getY() + localPoint2.y), i, j, l1, localCursor, l3, localPoint3.x,
//                    localPoint3.y, getDragSourceContext().getSourceActions(), paramArrayOfLong, paramMap);
//
//            if (l5 == 0L) {
//                throw new InvalidDnDOperationException("");
//            }
//            setNativeContext(l5);
        } catch (Exception localException1) {
            throw new InvalidDnDOperationException("failed to create native peer: " + localException1);
        }
        */

        SunDropTargetContextPeer.setCurrentJVMLocalSourceTransferable(paramTransferable);
        // try
        // {
        // Thread local1 = new Thread() {
        // @Override
        // public void run() {
        // long l = CDragSourceContextPeer.this.getNativeContext();
        // try {
        // CDragSourceContextPeer.this.doDragging(l);
        // } catch (Exception localException) {
        // localException.printStackTrace();
        // } finally {
        // CDragSourceContextPeer.this.releaseNativeDragSource(l);
        // CDragSourceContextPeer.access$302(CDragSourceContextPeer.this, null);
        // if (CDragSourceContextPeer.this.fDragCImage != null) {
        // CDragSourceContextPeer.this.fDragCImage.dispose();
        // CDragSourceContextPeer.access$402(CDragSourceContextPeer.this, null);
        // }
        // }
        // }
        // };
        // local1.start();
        // }
        // catch (Exception localException2)
        // {
        // long l6 = getNativeContext();
        // setNativeContext(0L);
        // releaseNativeDragSource(l6);
        // SunDropTargetContextPeer.setCurrentJVMLocalSourceTransferable(null);
        // throw new
        // InvalidDnDOperationException("failed to start dragging thread: " +
        // localException2);
        // }

    }

    public boolean writeItemsToPasteBoard(final NSView view, final List<String> items) {
        // The fileTypes argument is the list of fileTypes being promised.
        // The array elements can consist of file extensions and HFS types
        // encoded
        // with the NSHFSFileTypes method fileTypeForHFSTypeCode. If promising a
        // directory
        // of files, only include the top directory in the array.
        final NSMutableArray fileTypes = NSMutableArray.array();
        for (String item : items) {
            File path = new File("/cocoa.txt");
            if (path.isFile()) {
                if (true) {
                    fileTypes.addObject(NSString.stringWithString("txt"));
                } else {
                    fileTypes.addObject(NSString.stringWithString(NSFileManager.NSFileTypeRegular));
                }
            } else if (path.isDirectory()) {
                fileTypes.addObject(NSString.stringWithString("'fldr'")); // NSFileTypeForHFSTypeCode('fldr')
            } else {
                fileTypes.addObject(NSString.stringWithString(NSFileManager.NSFileTypeUnknown));
            }
        }
        /*
        NSEvent event = NSApplication.sharedApplication().currentEvent();
        if (event != null) {
            NSPoint dragPosition = view.convertPoint_fromView(event.locationInWindow(), null);
            NSRect imageRect = new NSRect(new NSPoint(dragPosition.x.doubleValue() - 16, dragPosition.y.doubleValue() - 16), new NSSize(32, 32));
            view.dragPromisedFilesOfTypes(fileTypes, imageRect, new DragProvider().id(), true, event);
            // @see
            // http://www.cocoabuilder.com/archive/message/cocoa/2003/5/15/81424
            return true;
        }
        */
        return false;
    }

}
